package com.example.ssm.common.component;

import com.example.ssm.service.SysUserService;
import com.example.ssm.service.impl.MyUserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

/**
 * 使用基于注解配置的方式实现spring security安全框架
 * spring security 的配置类
 *
 * @author yaojianfeng
 */
@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


    /**
     * 密码编码器
     *
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        System.out.println("配置密码编码器...");
//        return NoOpPasswordEncoder.getInstance();
        return new BCryptPasswordEncoder();
    }



    /**
     * 安全拦截机制
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //关闭csrf防护
        http.csrf().disable()
                .authorizeRequests()
                //给用户设置权限资源的对应关系,必须有对应的权限才可以
                .antMatchers("/sys/r1").hasAuthority("p1")
                .antMatchers("/sys/r2").hasAuthority("p2")
                //所有的/r/**的请求必须认证通过
                .antMatchers("/r/**").authenticated()
                //除了/r/**,其它的请求可以访问
                .anyRequest().permitAll()
                .and()
                //允许表单登录
                .formLogin()
                .successForwardUrl("/sys/login-success")
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.ALWAYS)
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login");
    }
}
